import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  Req,
  UseGuards,
  ClassSerializerInterceptor,
  UseInterceptors,
  UploadedFile,
} from '@nestjs/common';
import { PostService } from './post.service';
import { CreatePostDto } from './dto/create-post.dto';
import { UpdatePostDto } from './dto/update-post.dto';
import { ApiConsumes, ApiOperation } from '@nestjs/swagger';
import { FileInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { extname } from 'path';
import * as multer from 'multer';
@UseInterceptors(ClassSerializerInterceptor)
@Controller('post')
export class PostController {
  constructor(private readonly postService: PostService) {}

  // @ApiOperation({ summary: '发布帖子（附带图片上传）' })
  // @ApiConsumes('multipart/form-data')
  // @Post()
  // @UseInterceptors(
  //   FileInterceptor('file', {
  //     storage: diskStorage({
  //       destination: './uploads',
  //       filename: (_req, file, cb) => {
  //         const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
  //         const ext = extname(file.originalname);
  //         cb(null, `${uniqueSuffix}${ext}`);
  //       },
  //     }),
  //   }),
  // )
  // create(
  //   @UploadedFile() file: Express.Multer.File,
  //   @Body() body: any,
  //   @Req() req,
  // ) {
  //   return this.postService.createWithImage(file, body, req.user.id);
  // }
  @ApiOperation({ summary: '发布帖子（附带图片上传）' })
  @ApiConsumes('multipart/form-data')
  @Post()
  @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage({
        destination: './uploads',
        filename: (_req, file, cb) => {
          const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
          const ext = extname(file.originalname);
          cb(null, `${uniqueSuffix}${ext}`);
        },
      }),
    }),
  )
  async create(
    @UploadedFile() file: Express.Multer.File,
    @Body() body: any,
    @Req() req,
  ) {
    return this.postService.createWithImage(file, body, req.user.id);
  }

  @ApiOperation({ summary: '查询所有帖子' })
  @Get()
  findAll() {
    return this.postService.findAll();
  }

  @ApiOperation({ summary: '查询单个帖子' })
  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.postService.findById(+id);
  }

  @ApiOperation({ summary: '修改帖子' })
  @Patch(':id')
  update(
    @Param('id') id: string,
    @Body() updatePostDto: UpdatePostDto,
    @Req() req,
  ) {
    return this.postService.update(+id, updatePostDto, req.user.id);
  }

  @ApiOperation({ summary: '删除帖子' })
  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.postService.remove(+id);
  }
  @ApiOperation({ summary: '分页获取帖子列表' })
@Get('/list/:page/:pageSize')
findPaginated(
  @Param('page') page: string,
  @Param('pageSize') pageSize: string
) {
  return this.postService.findPaginated(+page || 1, +pageSize || 10);
}
}